/** 
 * 动态加载组件和HOC
 */

import React from 'react';

type DynamicComponentProps = {
    importer: () => Promise<any>;
    componentProps?: {[name: string]: any};
};

class DynamicComponent extends React.Component<DynamicComponentProps> {

    loadedComponent: any = undefined;

    isDisposed: boolean = false;

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.importer().then(mod => {
            if (this.isDisposed) return;
            this.loadedComponent = mod.default;
            this.forceUpdate();
        });
    }

    componentWillUnmount() {
        this.isDisposed = true;
    }

    render() {

        const Comp = this.loadedComponent;

        if (!Comp) return null;

        const { componentProps } = this.props;
        return <Comp {...(componentProps || {})} />;
    }
}

export const dynamic = (importer) => {
    return () => {
        return <DynamicComponent importer={importer} />;
    }
};

export default DynamicComponent;
